package org.jpush.core.stats;

import java.util.HashMap;
import java.util.Map;

public class DistributionMeasure extends Measure
{
	private Map<String, Double> mappedValues =
		new HashMap<String, Double>();

	public DistributionMeasure(String name)
	{
		super(name);
	}

	public void addObservation(MeasureArgs args)
	{
	    if (!(args instanceof DistributionMeasureArgs))
	    	return;

	    DistributionMeasureArgs myArgs = (DistributionMeasureArgs) args;

	    Double d = mappedValues.get(myArgs.serviceName);
	    if (d == null)
	    {
	    	mappedValues.put(myArgs.serviceName, new Double(myArgs.value));
	    }
	    else
	    {
	    	mappedValues.put(myArgs.serviceName, new Double(d.doubleValue() + myArgs.value));
	    }
	}


	public String collectAndReset(String timeStamp)
	{
	    //Collect
		StringBuffer sb = new StringBuffer();
		sb.append("<").append(name).append(">");
		for (Map.Entry<String, Double> entry :mappedValues.entrySet())
		{
			sb.append("<").append(entry.getKey());
			sb.append(" val=\"").append(entry.getValue()).append("\"/>");
		}
		sb.append("</").append(name).append(">");

	    //Reset
	    mappedValues.clear();

	    return sb.toString();
	}
}
